<?php
/**
 * Created by PhpStorm.
 * Author: kaodou
 * Date: 2017/10/17
 * Time: 15:07
 */
namespace App\Http\Admin\Permission\Controllers;

use App\Eloquent\Ygt\ProcessOrdertype;
use Framework\BaseClass\Http\Admin\Controller;
use App\Http\Admin\Website\Models\Menu;
use App\Eloquent\Ygt\Privilege;
use App\Eloquent\Ygt\Permission;
use App\Eloquent\Ygt\Process;
use App\Eloquent\Ygt\FieldLimit;
use App\Eloquent\Ygt\OrderFieldCompany;


class IndexController extends Controller
{

    public function getPermissionList()
    {
        if (request()->isMethod('post')) {

            $typeid = request('type_id',1);
            $typeAction = request('type_action',1);
            $nodeid = request('node_id',1);

            $privilegeIds = request('privilege_id',[]);
            $delPrivilegeIds = request('del_privilege_id');
            $data = [
                'type_id'=>$typeid,
                'type_action'=>$typeAction,
                'node_id'=>$nodeid,
            ];

            $insertData = [];
            foreach ($privilegeIds as $v){
                $insertData[] = array_merge($data,['privilege_id'=>$v]);
            }

            $permissionModel = new Permission();
            if($delPrivilegeIds){
                $permissionModel->del(array_merge($data,['privilege_id'=>['notIn',$delPrivilegeIds]]));
            }else{
                $permissionModel->del($data);
            }

//            dd($insertData);
            if($insertData){
                $permissionModel->insertData($insertData);
            }

            return $this->ajaxSuccess();


        }

        $typeid = request('type_id',1);
        $typeAction = request('type_action',1);
        $nodeid = request('node_id',1);

        $adminUser          = request()->user('admin')->toArray();
        $company_id         = $adminUser['company_id'];
        $privilege         = collect(Privilege::getList( ['company_id'=>$company_id], 'id,title' )->toArray());

        $list = $this->getAllPrivilegeNodePermission($typeid, $typeAction ,$nodeid,$company_id)->toArray();

        if($typeAction == 4){
            //提交动作增加排序值
            foreach ($list as $key => $value){
                $where = [];
                $where['ordertype_process_id'] = $nodeid;
                $where['privilege_id'] = $value['id'];
                $where['action_type'] = $typeAction;

                $ordertypeProcessPrivilegeSortObj = \App\Eloquent\Ygt\OrdertypeProcessPrivilegeSort::where($where)->first();
                $privilegeSort = 0;
                if($ordertypeProcessPrivilegeSortObj){
                    $privilegeSort = $ordertypeProcessPrivilegeSortObj->sort;
                }
                $list[$key]['sort'] = $privilegeSort;

            }
        }


        return $this->view('set-permission', compact('list','typeid','nodeid','typeAction'));
    }


    /**
     * @param $typeid 分类
     * @param $nodeid 节点
     * 获取节点 所有角色 权限
     */
    private function getAllPrivilegeNodePermission($typeid,$typeAction,$nodeid,$company_id){

        $fields=['ygt_privilege.*','ygt_permission.id as permission_id'];

        $list = Privilege::leftJoin('ygt_permission', function ($join) use($typeid,$nodeid,$typeAction,$company_id) {
            $join->on('ygt_permission.privilege_id', '=', 'ygt_privilege.id')
                ->where('ygt_permission.type_id', '=', $typeid)
//                ->where('ygt_permission.company_id', '=', $company_id)
                ->where('ygt_permission.type_action', '=', $typeAction)
                ->where('ygt_permission.node_id', '=', $nodeid);
        })
            ->where('ygt_privilege.company_id',$company_id)
            ->orderBy('ygt_privilege.id','desc')
            ->select($fields)->get();

        return $list;
    }

    public function baseFieldsSet(){
        if (request()->isMethod('post')) {
            $processOrdertypeId = request('process_ordertype_id');
            $privilegeId = request('privilege_id');

            $basefields = request('basefields');
            $baselimits = implode(',',$basefields);

            $basewhere = ['process_ordertype_id'=>$processOrdertypeId,'privilege_id'=>$privilegeId,'type'=>2];
            $basedata = ['limits'=>$baselimits];
            $result = FieldLimit::updateOrCreate($basewhere, $basedata);
            if($result){
                return $this->ajaxSuccess();
            }else{
                return $this->ajaxFail();
            }
        }

        $processOrdertypeId = request('process_ordertype_id');
        $privilegeId = request('privilege_id');


        //基础信息字段
        $adminUser          = request()->user('admin')->toArray();
        $companyId         = $adminUser['company_id'];
        $baseFields         = OrderFieldCompany::getActiveFieldList( $companyId );

        $oldbaseFields = FieldLimit::where('process_ordertype_id',$processOrdertypeId)->where('privilege_id',$privilegeId)->where('type',2)->first();

        if($oldbaseFields['limits'] !== null){
            $limitsBase = explode(',',$oldbaseFields['limits']);
        }else{
            $limitsBase = [];
        }
        $baseFields = collect($baseFields);
        $baseFields->transform(function($item) use($limitsBase){
            $item['is_check'] = in_array($item['id'],$limitsBase) ? 1 : 0;
            return $item;
        });

        return $this->view('base-fields-set',compact( 'baseFields', 'processOrdertypeId', 'privilegeId'));
    }


    public function lookActionSet(){
        if (request()->isMethod('post')) {
            $processOrdertypeId = request('process_ordertype_id');
            $privilegeId = request('privilege_id');
            $fields = request('fields');
            $limits = implode(',',$fields);

            $where = ['process_ordertype_id'=>$processOrdertypeId,'privilege_id'=>$privilegeId,'type'=>1];
            $data = ['limits'=>$limits];
            $result = FieldLimit::updateOrCreate($where, $data);
            if($result){
                return $this->ajaxSuccess();
            }else{
                return $this->ajaxFail();
            }
        }

        $processOrdertypeId = request('process_ordertype_id');
        $privilegeId = request('privilege_id');

        $processOrdertypeInfo = ProcessOrdertype::where('id',$processOrdertypeId)->first();

        //工序字段列表
        $processFields = Process::getFieldListByProcessId($processOrdertypeInfo->process_id);

        $oldProcessFields = FieldLimit::where('process_ordertype_id',$processOrdertypeId)->where('privilege_id',$privilegeId)->where('type',1)->first();

        if($oldProcessFields['limits'] !== null){
            $limitsProcess = explode(',',$oldProcessFields['limits']);
        }else{
            $limitsProcess = [];
        }

        $processFields = collect($processFields);
        $processFields->transform(function($item) use($limitsProcess){
            $item['is_check'] = in_array($item['id'],$limitsProcess) ? 1 : 0;
            return $item;
        });

        return $this->view('look-action-set',compact('processFields', 'processOrdertypeId', 'privilegeId'));
    }


    public function needPieceSet(){
        if (request()->isMethod('post')) {
            $processOrdertypeId = request('process_ordertype_id');
            $privilegeId = request('privilege_id');
            $fields = request('need_piece');
            $limits = 0;
            if($fields){
                $limits = 1;
            }

            $where = ['process_ordertype_id'=>$processOrdertypeId,'privilege_id'=>$privilegeId,'type'=>3];
            $data = ['limits'=>$limits];
            $result = FieldLimit::updateOrCreate($where, $data);
            if($result){
                return $this->ajaxSuccess();
            }else{
                return $this->ajaxFail();
            }
        }

        $processOrdertypeId = request('process_ordertype_id');
        $privilegeId = request('privilege_id');

        $processOrdertypeInfo = ProcessOrdertype::where('id',$processOrdertypeId)->first();

        //工序字段列表
        $processFields = Process::getFieldListByProcessId($processOrdertypeInfo->process_id);

        $oldProcessFields = FieldLimit::where('process_ordertype_id',$processOrdertypeId)->where('privilege_id',$privilegeId)->where('type',3)->first();

        $needPiece = 0;
        if($oldProcessFields['limits'] !== null){
            $needPiece = $oldProcessFields['limits'];
        }

        return $this->view('need-piece-set',compact('needPiece', 'processOrdertypeId', 'privilegeId'));
    }

    //设置成品入库
    public function finishedProductSet(){
        if (request()->isMethod('post')) {
            $processOrdertypeId = request('process_ordertype_id');
            $privilegeId = request('privilege_id');
            $fields = request('able_finished_product');
            $limits = 0;
            if($fields){
                $limits = 1;
            }

            $where = ['process_ordertype_id'=>$processOrdertypeId,'privilege_id'=>$privilegeId,'type'=>4];
            $data = ['limits'=>$limits];
            $result = FieldLimit::updateOrCreate($where, $data);
            if($result){
                return $this->ajaxSuccess();
            }else{
                return $this->ajaxFail();
            }
        }

        $processOrdertypeId = request('process_ordertype_id');
        $privilegeId = request('privilege_id');

        $processOrdertypeInfo = ProcessOrdertype::where('id',$processOrdertypeId)->first();

        $oldProcessFields = FieldLimit::where('process_ordertype_id',$processOrdertypeId)->where('privilege_id',$privilegeId)->where('type',4)->first();

        $ableFinishedProduct = 0;
        if($oldProcessFields['limits'] !== null){
            $ableFinishedProduct = $oldProcessFields['limits'];
        }

        return $this->view('finished-product-set',compact('ableFinishedProduct', 'processOrdertypeId', 'privilegeId'));
    }


    public function privilegeSortSet(){
        if (request()->isMethod('post')) {
            $processOrdertypeId = request('process_ordertype_id');
            $privilegeId = request('privilege_id');
            $privilegeSort = request('privilege_sort');
            $actionType = request('action_type');

            $where = ['ordertype_process_id'=>$processOrdertypeId,'privilege_id'=>$privilegeId,'action_type'=>$actionType];
            $data = ['sort'=>$privilegeSort];
            $result = \App\Eloquent\Ygt\OrdertypeProcessPrivilegeSort::updateOrCreate($where, $data);
            if($result){
                return $this->ajaxSuccess();
            }else{
                return $this->ajaxFail();
            }
        }

        $processOrdertypeId = request('process_ordertype_id');
        $privilegeId = request('privilege_id');
        $actionType = request('action_type');

        $ordertypeProcessPrivilegeSortRow = \App\Eloquent\Ygt\OrdertypeProcessPrivilegeSort::where('ordertype_process_id',$processOrdertypeId)->where('privilege_id',$privilegeId)->where('action_type',$actionType)->first();


        $privilegeSort = 0;
        if($ordertypeProcessPrivilegeSortRow !== null){
            $privilegeSort = $ordertypeProcessPrivilegeSortRow['sort'];
        }

        return $this->view('privilege-sort-set',compact('privilegeSort', 'processOrdertypeId', 'privilegeId'));
    }




}